package com.lw.lost.activity

import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.lw.lost.adapters.FriendRequestAdapter
import com.lw.lost.databinding.ActivityFriendRequestBinding
import com.lw.lost.db.DBlost
import com.lw.lost.models.FriendRequest
import com.lw.lost.utils.PreferenceUtils

class FriendRequestActivity : AppCompatActivity() {

    private lateinit var binding: ActivityFriendRequestBinding
    private lateinit var db: DBlost
    private lateinit var requestAdapter: FriendRequestAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityFriendRequestBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = "好友请求"

        db = DBlost(this)
        setupRecyclerView()
        loadRequests()
    }

    private fun setupRecyclerView() {
        requestAdapter = FriendRequestAdapter(
            onAccept = { request -> handleRequest(request, true) },
            onReject = { request -> handleRequest(request, false) }
        )
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = requestAdapter
        }
    }

    private fun loadRequests() {
        val cursor = db.friendRequestDao.getRequestsByReceiverId(PreferenceUtils.getUserId(this))
        val requests = mutableListOf<FriendRequest>()

        cursor.use { cursor ->
            while (cursor.moveToNext()) {
                requests.add(
                    FriendRequest(
                        requestId = cursor.getLong(cursor.getColumnIndexOrThrow("requestId")),
                        senderId = cursor.getLong(cursor.getColumnIndexOrThrow("senderId")),
                        senderName = cursor.getString(cursor.getColumnIndexOrThrow("senderName")),
                        senderAvatar = cursor.getString(cursor.getColumnIndexOrThrow("senderAvatar")),
                        message = cursor.getString(cursor.getColumnIndexOrThrow("message")),
                        createTime = cursor.getString(cursor.getColumnIndexOrThrow("createTime"))
                    )
                )
            }
        }

        requestAdapter.submitList(requests)

        // 更新空状态显示
        binding.emptyView.visibility = if (requests.isEmpty()) View.VISIBLE else View.GONE
        binding.recyclerView.visibility = if (requests.isEmpty()) View.GONE else View.VISIBLE
    }

    private fun handleRequest(request: FriendRequest, isAccepted: Boolean) {
        val action = if (isAccepted) "同意" else "拒绝"
        AlertDialog.Builder(this)
            .setTitle("确认操作")
            .setMessage("确定要${action}该好友请求吗？")
            .setPositiveButton("确定") { _, _ ->
                // 更新请求状态
                val status = if (isAccepted) 1 else 2
                val result = db.friendRequestDao.updateRequestStatus(request.requestId, status)

                if (result > 0) {
                    if (isAccepted) {
                        // 添加好友关系
                        val values = android.content.ContentValues().apply {
                            put("userId", request.senderId)
                            put("matchedUserId", PreferenceUtils.getUserId(this@FriendRequestActivity))
                        }
                        db.writableDatabase.insert("match_records", null, values)
                    }
                    loadRequests() // 刷新列表
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
} 